<template>
  <div class="agv-list">
    <div class="agv-header">
      <q-toolbar class="agv-toolbar shadow-1">
        <q-toolbar-title v-if="!showFilterInput">{{ t('agvDeviceList') }}</q-toolbar-title>
        <q-input v-if="showFilterInput" v-model="filterText" :placeholder="'筛选车号、IP'"
                 dense outlined type="tel"
                 class="filter-input" ref="filterInputRef" autofocus>
          <template v-slot:append>
            <q-icon name="close" @click="clearFilter" />
          </template>
        </q-input>
        <!-- 筛选图标按钮 -->
        <q-btn v-else flat round icon="search" @click="toggleFilterInput" class="filter-btn" />

        <!-- 更多操作菜单按钮 -->
        <q-btn-dropdown flat round class="more-actions-btn" dropdown-icon="more_vert">
          <q-list>
            <q-item clickable v-close-popup @click="handleShowAddAgvDialog">
              <q-item-section avatar>
                <q-icon name="add" color="primary" />
              </q-item-section>
              <q-item-section>
                <q-item-label>{{ t('addAgvDevice') }}</q-item-label>
              </q-item-section>
            </q-item>

            <q-item clickable v-close-popup @click="handleRefresh">
              <q-item-section avatar>
                <q-icon name="refresh" color="secondary" />
              </q-item-section>
              <q-item-section>
                <q-item-label>{{ t('refresh') || '刷新' }}</q-item-label>
              </q-item-section>
            </q-item>

            <q-separator />

            <q-item clickable v-close-popup @click="showCustomAgvManager = true">
              <q-item-section avatar>
                <q-icon name="settings" color="orange" />
              </q-item-section>
              <q-item-section>
                <q-item-label>管理自定义车辆</q-item-label>
              </q-item-section>
            </q-item>
          </q-list>
        </q-btn-dropdown>
      </q-toolbar>
    </div>

    <div class="agv-content">
      <q-list>
        <q-item v-for="(agv, index) in filteredAgvList" :key="agv.Vid" clickable :class="[
          'agv-item',
          { 'agv-selected': selectedAgvId === (''+agv.Vid) },
          { 'agv-odd': index % 2 === 1 },
          { 'agv-even': index % 2 === 0 }
        ]" @click="selectAgv(agv.Vid)">
          <div class="q-list-item">

            <!-- AGV信息内容 -->
            <q-item-section class="agv-content">
              <!-- 第一行：车号和IP -->
              <q-item-label class="agv-header">
                <div class="agv-id-section">
                  <q-chip :color="getStatusColor(agv)" text-color="white" class="agv-chip" icon="assignment_ind">
                    {{ agv.Vid }}
                  </q-chip>
                  <q-chip v-if="agv.IpAddr && agv.IpAddr !== '-'" size="sm" outline>
                    {{ agv.IpAddr }}
                  </q-chip>
                  <q-chip v-else size="sm" outline>
                    IP未知
                  </q-chip>
                </div>


                <q-chip :color="getModeColor(agv)" text-color="white" size="xs" class="agv-mode-chip">
                  {{ getModeText(agv) }}
                </q-chip>
                <q-icon :name="getStatusIcon(agv)" :color="getStatusColor(agv)" size="sm" />


              </q-item-label>

              <!-- 第二行：位置和模式 -->
              <q-item-label class="agv-info">
                <q-chip v-if="getPoseText(agv)" size="sm" icon="fmd_good">
                  {{ getPoseText(agv) }}
                </q-chip>
                <q-chip v-else size="sm" icon="location_off" outline>
                  姿态未知
                </q-chip>

                <div class="agv-battery-section">
                  <q-circular-progress :value="agv.Battery" :color="getBatteryColor(agv.Battery)"
                                       size="24px" :thickness="0.3" show-value track-color="grey-3" font-size="10px"
                                       class="agv-battery-progress">
                    {{ agv.Battery }}%
                  </q-circular-progress>
                </div>
              </q-item-label>
            </q-item-section>
          </div>
          <div class="q-list-item-toolbar">
            <q-btn label="遥控器" unelevated color="brown-5" outline size="sm" v-if="agv.isOnline"
                   @click="() => {showRemoteControlDialog = true;remoteControlAgv=agv}" icon="gamepad" />
          </div>
        </q-item>
      </q-list>
    </div>
  </div>
  <q-dialog v-model="showRemoteControlDialog" persistent :maximized="true">
    <RemoteControl @closeDialog="() => showRemoteControlDialog = false" :agv="remoteControlAgv" />
  </q-dialog>
  <!-- 移动端添加AGV对话框 -->
  <q-dialog v-model="showAddDialog" persistent>
    <q-card class="agv-dialog-card">
      <q-card-section class="row items-center q-pb-none agv-dialog-header">
        <div class="text-h6">{{ t('addAgvDevice') }}</div>
        <q-space />
        <q-btn icon="close" flat round dense v-close-popup />
      </q-card-section>

      <q-card-section class="agv-dialog-content">
        <q-form @submit="handleAddAgv" class="q-gutter-md">
          <q-input v-model="newAgv.id" :label="t('vehicleNumber')" type="number"
                   :rules="[val => !!val || t('vehicleNumberRequired'), val => !isIdDuplicate(val) || t('vehicleNumberExists')]"
                   outlined dense autofocus />

          <q-input v-model="newAgv.ip" :label="t('ipAddress')" type="tel"
                   :rules="[
            val => !!val || t('ipAddressRequired'),
            val => isValidIp(val) || t('invalidIpFormat'),
            val => !isIpDuplicate(val) || t('ipAddressExists')
          ]" outlined dense />
        </q-form>
      </q-card-section>

      <q-card-actions align="right" class="agv-dialog-actions">
        <q-btn flat :label="t('cancel')" color="primary" v-close-popup />
        <q-btn flat :label="t('confirm')" color="primary" @click="handleAddAgv" />
      </q-card-actions>
    </q-card>
  </q-dialog>

  <!-- 自定义车辆管理对话框 -->
  <q-dialog v-model="showCustomAgvManager" persistent>
    <q-card class="agv-dialog-card" style="min-width: 600px;">
      <q-card-section class="row items-center q-pb-none agv-dialog-header">
        <div class="text-h6">管理自定义车辆</div>
        <q-space />
        <q-btn icon="close" flat round dense v-close-popup />
      </q-card-section>

      <q-card-section class="agv-dialog-content">
        <div class="q-gutter-md">
          <!-- 添加新自定义车辆 -->
          <div class="text-subtitle2 q-mb-sm">添加新自定义车辆</div>
          <div class="row q-gutter-sm">
            <q-input v-model="newCustomAgv.agvId" label="车号" outlined dense class="col-4" />
            <q-input v-model="newCustomAgv.ip" label="IP地址" outlined dense class="col-4" />
            <q-btn color="primary" label="添加" @click="handleAddCustomAgv" class="col-3" />
          </div>

          <q-separator class="q-my-md" />

          <!-- 自定义车辆列表 -->
          <div class="text-subtitle2 q-mb-sm">自定义车辆列表</div>
          <q-list separator>
            <q-item v-for="customAgv in agvStore.customAgvList" :key="customAgv.agvId">
              <q-item-section>
                <q-item-label>
                  <q-chip :color="customAgv.isOnline ? 'green' : 'grey'" text-color="white" size="sm">
                    {{ customAgv.agvId }}
                  </q-chip>
                  <span class="q-ml-sm">{{ customAgv.ip }}</span>
                </q-item-label>
              </q-item-section>
              <q-item-section side>
                <div class="row q-gutter-xs">
                  <q-btn flat round icon="edit" color="primary" size="sm" @click="handleEditCustomAgv(customAgv)" />
                  <q-btn flat round icon="delete" color="negative" size="sm"
                         @click="handleDeleteCustomAgv(customAgv.agvId)" />
                </div>
              </q-item-section>
            </q-item>
            <q-item v-if="agvStore.customAgvList.length === 0">
              <q-item-section class="text-center text-grey-6">
                暂无自定义车辆
              </q-item-section>
            </q-item>
          </q-list>
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>

  <!-- 编辑自定义车辆对话框 -->
  <q-dialog v-model="showEditCustomAgvDialog" persistent>
    <q-card class="agv-dialog-card">
      <q-card-section class="row items-center q-pb-none agv-dialog-header">
        <div class="text-h6">编辑自定义车辆</div>
        <q-space />
        <q-btn icon="close" flat round dense v-close-popup />
      </q-card-section>

      <q-card-section class="agv-dialog-content">
        <div class="q-gutter-md">
          <q-input v-model="editingCustomAgv.agvId" label="车号" outlined dense readonly />
          <q-input v-model="editingCustomAgv.ip" label="IP地址" outlined dense />
        </div>
      </q-card-section>

      <q-card-actions align="right" class="agv-dialog-actions">
        <q-btn flat :label="t('cancel')" color="primary" v-close-popup />
        <q-btn flat :label="t('confirm')" color="primary" @click="handleSaveCustomAgv" />
      </q-card-actions>
    </q-card>
  </q-dialog>

  <!-- 添加文本显示对话框 -->
  <q-dialog v-model="showTextDialog" persistent>
    <q-card class="text-dialog-card">
      <q-card-section class="row items-center q-pb-none dialog-header">
        <div class="text-h6">{{ textDialogTitle }}</div>
        <q-space />
        <q-btn icon="close" flat round dense v-close-popup />
      </q-card-section>

      <q-card-section class="dialog-content">
        <q-scroll-area style="height: 300px; max-width: 100%;">
          <div class="text-content">
            {{ displayText }}
          </div>
        </q-scroll-area>
      </q-card-section>

      <q-card-actions align="right" class="dialog-actions">
        <q-btn flat :label="t('close')" color="primary" v-close-popup />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>
<script setup lang="ts">
import { computed, nextTick, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import RemoteControl from './RemoteControl.vue';
import useRcs2AgvStore, { CustomAgvInfo, RcsAgvInfoVo } from 'src/stores/useRcs2AgvStore';
import { useRouter } from 'vue-router';

const router = useRouter();
const { t } = useI18n();
const agvStore = useRcs2AgvStore();
const agvList = computed(() => agvStore.agvList);

const showRemoteControlDialog = ref(false);
const remoteControlAgv = ref<RcsAgvInfoVo | null>(null);
const filterText = ref('');
const showFilterInput = ref(false);
const filterInputRef = ref<any>(null);
const selectedAgvId = ref<string>('');
const showAddDialog = ref(false);
const newAgv = ref({ id: '', ip: '' });

// 自定义车辆管理相关变量
const showCustomAgvManager = ref(false);
const showEditCustomAgvDialog = ref(false);
const newCustomAgv = ref({ agvId: '', ip: '' });
const editingCustomAgv = ref({ agvId: '', ip: '' });

// 文本显示对话框相关变量
const showTextDialog = ref(false);
const displayText = ref('');
const textDialogTitle = ref('文本内容');

// 显示文本对话框的方法
function showTextContent(title: string, text: string) {
  textDialogTitle.value = title;
  displayText.value = text;
  showTextDialog.value = true;
}

function handleShowAddAgvDialog() {
  showAddDialog.value = true;
}

function handleRefresh() {
  agvStore.refreshData();
}


// 获取模式颜色
function getModeColor(agv: Partial<RcsAgvInfoVo>): string {
  return getStatusColor(agv);
}

// 获取状态颜色
function getStatusColor(agv: Partial<RcsAgvInfoVo>): string {
  // 以 displayStatus 为准
  switch (getDisplayStatus(agv)) {
    case 4096: // shutdown 关机
      return 'grey';
    case 256: // offline 掉线
      return 'grey';
    case 128: // error 异常
      return 'red';
    case 64: // agvError 物理错误
      return 'red';
    case 1024: // auto 自动
      return 'green';
    case 512: // control 管制
      return 'orange';
    case 32: // pause 暂停
      return 'yellow';
    case 8: // working 工作中
      return 'blue';
    case 4: // charge 充电
      return 'orange';
    case 2: // lowPower 低电
      return 'red';
    case 16: // lock 锁定
      return 'purple';
    case 11: // suspend 挂起
      return 'yellow';
    case 1: // idle 空闲
      return 'blue';
    default: // 默认
      return 'grey';
  }
}

function getPoseText(agv: Partial<RcsAgvInfoVo>) {
  if (typeof agv.CurrentX === 'undefined' || agv.CurrentY === null) {
    return;
  }
  return (agv.Location + ' (' + agv.CurrentX + ',' + agv.CurrentY + ')');
}

function getDisplayStatus(agv: Partial<RcsAgvInfoVo>): RcsDisplayStatus {
  if (_.isArray(agv.AllStatuses) && agv.AllStatuses[0]) {
    // return agv.AllStatuses[0] as RcsDisplayStatus;
    if (_.includes(agv.AllStatuses, 4096)) {
      return 4096;
    }
    if (_.includes(agv.AllStatuses, 256)) {
      return 4096;
    }
    if (_.includes(agv.AllStatuses, 64)) {
      return 64;
    }
    if (_.includes(agv.AllStatuses, 128)) {
      return 128;
    }
    return _.max(agv.AllStatuses);
  }
  return 0;
}

// 获取状态图标
function getStatusIcon(agv: Partial<RcsAgvInfoVo>): string {

  switch (getDisplayStatus(agv)) {
    case 4096: // shutdown 关机
      return 'power_settings_new';
    case 256: // offline 掉线
      return 'wifi_off';
    case 128: // error 异常
      return 'error';
    case 64: // agvError 物理错误
      return 'error_outline';
    case 1024: // auto 自动
      return 'auto_mode';
    case 512: // control 管制
      return 'control_camera';
    case 32: // pause 暂停
      return 'pause_circle';
    case 8: // working 工作中
      return 'moving';
    case 4: // charge 充电
      return 'battery_charging_full';
    case 2: // lowPower 低电
      return 'battery_alert';
    case 16: // lock 锁定
      return 'lock';
    case 11: // suspend 挂起
      return 'pause';
    case 1: // idle 空闲
      return 'mode_standby';
    default: // 默认
      return 'help';
  }
}

// 获取模式文本
function getModeText(agv: Partial<RcsAgvInfoVo>): string {

  switch (getDisplayStatus(agv)) {
    case 4096: // shutdown 关机
      return t('shutdown') || '关机';
    case 256: // offline 掉线
      return t('offline');
    case 128: // error 异常
      return t('error') || '异常';
    case 64: // agvError 物理错误
      return t('agvError') || '物理错误';
    case 1024: // auto 自动
      return t('auto') || '自动';
    case 512: // control 管制
      return t('control') || '管制';
    case 32: // pause 暂停
      return t('pause') || '暂停';
    case 8: // working 工作中
      return t('working') || '工作中';
    case 4: // charge 充电
      return t('charging');
    case 2: // lowPower 低电
      return t('lowPower') || '低电';
    case 16: // lock 锁定
      return t('lock') || '锁定';
    case 11: // suspend 挂起
      return t('suspend') || '挂起';
    case 1: // idle 空闲
      return t('idle');
    default: // 默认
      return t('unknown');
  }
}

// 获取电量颜色
function getBatteryColor(soc: number): string {
  if (soc > 60) return 'green';
  if (soc > 30) return 'orange';
  return 'red';
}

// 选择AGV
function selectAgv(vid: number) {
  // 触发选中变化事件
  const agv = agvList.value.find(agv => agv.Vid === vid) || null;
  if (agv?.IpAddr) {
    selectedAgvId.value = '' + vid;
    router.replace('/rt/agvList/' + agv.IpAddr).finally();

  } else if (agv?.IpAddr) {
    LCC.msg('not config IP, agvId:' + agv.IpAddr, { type: 'error' });

  } else {
    LCC.msg('not found id:' + vid, { type: 'error' });
  }
}

function handleShowRemoteControl() {
  showRemoteControlDialog.value = true;
}

// 筛选AGV列表
// 1. 如果输入包含空格：只筛选车号
// 2. 如果输入不包含空格：筛选车号和IP
const filteredAgvList = computed(() => {
  if (!filterText.value) {
    return agvList.value;
  }

  const filter = filterText.value;
  const filterLower = filter.toLowerCase();

  // 检查是否包含空格
  const containsSpace = filter.includes(' ');

  if (containsSpace) {
    // 包含空格：只筛选车号
    return agvList.value.filter(agv => {
      return ('' + agv.Vid) === filterLower.trim();
    });
  }

  // 不包含空格：筛选车号和IP
  return agvList.value.filter(agv => {
    return ('' + agv.Vid).includes(filterLower) ||
      _.toLower(agv.IpAddr).includes(filterLower);
  });
});

// 切换筛选输入框显示状态
function toggleFilterInput() {
  if (filterText.value) {
    // 如果有筛选文本，直接清空
    clearFilter();
  } else {
    // 显示筛选输入框
    showFilterInput.value = true;
    nextTick(() => {
      if (filterInputRef.value) {
        filterInputRef.value.focus();
      }
    });
  }
}

// 清空筛选
function clearFilter() {
  filterText.value = '';
  showFilterInput.value = false;
}

// 检查ID是否重复
function isIdDuplicate(id: string): boolean {
  return agvList.value.some(agv => agv.Vid === parseInt(id));
}

// 检查IP是否重复
function isIpDuplicate(ip: string): boolean {
  return agvList.value.some(agv => agv.IpAddr === ip);
}

// 验证IP地址格式
function isValidIp(ip: string): boolean {
  const ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
  return ipRegex.test(ip);
}

// 处理添加AGV
function handleAddAgv() {
  if (!newAgv.value.id || !newAgv.value.ip) {
    return;
  }

  if (isIdDuplicate(newAgv.value.id)) {
    return;
  }

  if (isIpDuplicate(newAgv.value.ip)) {
    return;
  }

  if (!isValidIp(newAgv.value.ip)) {
    return;
  }

  // 发射添加AGV事件
  agvStore.addCustomAgv({ agvId: newAgv.value.id, ip: newAgv.value.ip });

  // 清空表单并关闭对话框
  newAgv.value = { id: '', ip: '' };
  showAddDialog.value = false;
}

// 自定义车辆管理相关函数
function handleEditCustomAgv(customAgv: CustomAgvInfo) {
  editingCustomAgv.value = { ...customAgv };
  showEditCustomAgvDialog.value = true;
}

function handleSaveCustomAgv() {
  if (!editingCustomAgv.value.agvId || !editingCustomAgv.value.ip) {
    return;
  }

  if (isIdDuplicate(editingCustomAgv.value.agvId)) {
    return;
  }

  if (isIpDuplicate(editingCustomAgv.value.ip)) {
    return;
  }

  if (!isValidIp(editingCustomAgv.value.ip)) {
    return;
  }

  // 使用 addCustomAgv 来更新，因为它会检查重复并更新现有项
  agvStore.addCustomAgv({
    agvId: editingCustomAgv.value.agvId,
    ip: editingCustomAgv.value.ip
  });
  showEditCustomAgvDialog.value = false;
}

function handleDeleteCustomAgv(agvId: string) {
  if (confirm('确认删除这个自定义车辆吗？')) {
    agvStore.removeCustomAgv(agvId);
  }
}

function handleAddCustomAgv() {
  if (!newCustomAgv.value.agvId || !newCustomAgv.value.ip) {
    return;
  }

  if (isIdDuplicate(newCustomAgv.value.agvId)) {
    return;
  }

  if (isIpDuplicate(newCustomAgv.value.ip)) {
    return;
  }

  if (!isValidIp(newCustomAgv.value.ip)) {
    return;
  }

  agvStore.addCustomAgv({
    agvId: newCustomAgv.value.agvId,
    ip: newCustomAgv.value.ip
  });
  newCustomAgv.value = { agvId: '', ip: '' };
}
</script>
<style scoped>

.text-dialog-card {
  width: 90vw;
  max-width: 600px;
  border-radius: 16px;
}

.dialog-content {
  padding: 20px;
  min-height: 150px;
}

.text-content {
  font-family: monospace;
  white-space: pre-wrap;
  word-break: break-all;
}

.dialog-actions {
  border-top: 1px solid #e0e0e0;
  padding: 16px 24px;
}

.agv-list {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #fff;
}

.q-item__section--avatar {
  min-width: 40px;
}

.q-item__section--side {
  padding-right: 0;
}

.agv-header {
  color: #333;
  flex-shrink: 0;
}

.agv-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-width: 0;
  /* 防止flex子元素溢出 */
  min-height: 43px;
  background: #fff;
}

.filter-input {
  transition: all 0.3s ease;
  flex: 1;
}

.filter-btn {
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.agv-item {
  border: 1px solid #bababa;
  border-radius: 5px;
  padding: 0;
  position: relative;
  background: #f5f5f5;
  margin-bottom: 8px;
  cursor: pointer;
}

.agv-item:hover {
  box-shadow: 0 0 0 2px #fdd973 inset;
  outline: none;
  background: #f9eeca;
  border-color: transparent;
}

.agv-selected {
  box-shadow: 0 0 0 2px #fdd973 inset;
  outline: none;
  background: #f9eeca;
  border-color: transparent;
}

.agv-content {
  margin: 5px;
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  /* 防止横向滚动 */
  min-width: 0;
  /* 允许内容收缩 */
}

.agv-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.agv-id-section {
  display: flex;
  align-items: center;
  gap: 4px;
  flex: 1;
  overflow: hidden;
}

.agv-info {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.agv-pose {
  font-size: 0.8rem;
  color: #333;
  font-weight: 500;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.agv-mode-chip {
  font-size: 0.7rem;
}

.agv-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.agv-battery-section {
  display: flex;
  align-items: center;
  justify-content: center;
}

.agv-battery-progress {
  margin: 0;
}

.agv-progress-section {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.agv-progress-bar {
  flex: 1;
  height: 6px;
  border-radius: 3px;
}

.agv-progress-text {
  font-size: 0.7rem;
  color: #666;
  white-space: nowrap;
}

/* 移动端对话框样式 */
.agv-dialog-card {
  width: 90vw;
  max-width: 400px;
  border-radius: 16px;
}

.agv-dialog-content {
  padding: 24px;
}

.agv-dialog-actions {
  border-top: 1px solid #e0e0e0;
  padding: 16px 24px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .agv-toolbar {
    padding: 0 12px;
  }

  .agv-content {
    padding: 4px;
  }

  .agv-item {
    margin-bottom: 6px;
  }

  .agv-ip {
    max-width: 100px;
  }

  .agv-progress-section {
    max-width: 100%;
  }
}

/* 触摸优化 */
.agv-item {
  -webkit-tap-highlight-color: transparent;
  user-select: none;
}

.agv-item:active {
  transform: scale(0.98);
}

/* 滚动条样式 */
.agv-content::-webkit-scrollbar {
  width: 4px;
}

.agv-content::-webkit-scrollbar-track {
  background: transparent;
}

.agv-content::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 2px;
}

.agv-content::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.3);
}

.agv-list .q-item.no-wrap {
  flex-wrap: wrap;
}

.q-list-item {
  width: 100%;
  display: flex;
  flex-direction: row;
  padding: 0 3px;
}

.q-list-item-toolbar {
  width: 100%;
  padding: 0 5px 5px;
  display: flex;
  flex-direction: row;
  justify-content: right;
  gap: 8px;
}
</style>
